/*
 * @Description: Description
 * @Autor: Chen
 * @Date: 2020-08-26 11:13:49
 * @LastEditors: snzo.chen
 * @LastEditTime: 2023-05-30 16:02:36
 */
import { Inject, Injectable } from '@angular/core';
import { API_CONFIG_UC, ServicesModule } from '../services/services.module';
import { Observable } from 'rxjs';
import { map } from 'rxjs/internal/operators';
import { AnyJson } from '../services/data-types/common.type';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { StorageService } from '../services/storage.service';
import Util from 'src/assets/utils/util';
import { Base64 } from 'js-base64';
declare var aesUtil: any;

@Injectable({
  providedIn: ServicesModule
})
export class AuthService {

  constructor(
    private http: HttpClient,
    private router: Router,
    private storageServe: StorageService,
    @Inject(API_CONFIG_UC) private uc: string
  ) { }
  isLoggedIn = false;
  redirectUrl!: string;
  operator!: string;
  isInstitution!: string;
  userInfo: any;
  matchSpread!: string;
  token!: string;
  cardNo!: string;
  cardNoOfData: any[] = [];
  backUrl!: string;
  ssoParams!: string;
  isLoginByCardNo!: boolean;

  /**
   * 手机号/身份证号/神通卡号-密码进行登陆操作
   */
  ValidateCardByPass(params: AnyJson): Observable<AnyJson> {
    const encryptKey = '1kQdPy54X23VjXT7f9nl6d4f2m8238ET';
    const aesRandomKey = aesUtil.getKey();
    const aesKey = aesUtil.encrypt(aesRandomKey, encryptKey);
    const data = aesUtil.encrypt(params, aesRandomKey);
    const body = new URLSearchParams();
    body.set('aesKey', aesKey);
    body.set('data', data);
    body.set('timestamp', (new Date().getTime()).toString());
    const headers = { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' };
    return this.http.post(this.uc + '/api/uc/user/ValidateCardByPass', body, { headers })
      .pipe(map((res) => res as AnyJson));
  }

  /**
   * 手机号-验证码登录
   */
  loginByPhoneAndCode(params: AnyJson): Observable<AnyJson> {
    const body = Util.formatSearchParams(params);
    const headers = { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' };
    return this.http.post(this.uc + '/api/uc/user/loginByPhoneAndCode', body, { headers })
      .pipe(map((res) => res as AnyJson));
  }


  /**
   * 单点登录
   */
  ssoGetUser(params: AnyJson): Observable<AnyJson> {
    const body = Util.formatSearchParams(params);
    const headers = {
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
      Authorization: this.token
    };
    return this.http.post('https://contest.snzo.cn:8082/card/ssoGetUser', body, { headers })
      .pipe(map((res) => res as AnyJson));
  }

  /**
   * 登出
   */
  logout(): Observable<AnyJson> {
    const headers = {
      Authorization: this.token
    };
    return this.http.get(this.uc + '/api/uc/user/logout/' + this.userInfo.cardNo, { headers })
      .pipe(map((res) => res as AnyJson));
  }

  doLogin(params: AnyJson): Observable<AnyJson> {
    return this.http.post('/api/ValidateCardByPass/' + params.j_username + '/' + params.j_password, null)
      .pipe(map((res) => res as AnyJson));
  }

  // logout(): void {
  //   this.storageServe.removeStorage('isLoggedIn');
  //   this.isLoggedIn = false;
  //   this.router.navigate(['/home']);
  // }

  /**
   * 设置登录状态并保存本地数据缓存
   */
  setStorageInfo() {
    if (this.isLoginByCardNo) {
      this.storageServe.setStorage([
        { key: 'ucUserInfo', value: JSON.stringify(this.userInfo) },
        { key: 'token', value: this.token }
      ]);
    } else {
      this.storageServe.setStorage([
        { key: 'ucUserInfo', value: JSON.stringify(this.userInfo) },
        { key: 'token', value: this.token },
        { key: 'cardNoOfData', value: JSON.stringify(this.cardNoOfData) }
      ]);
    }
    this.isLoggedIn = true;
    // 设置登录状态
    this.routerUrl();
  }

  /**
   * 设置登录状态
   */
  routerUrl() {
    if (this.ssoParams) {
      const ssoStr = Base64.decode(this.ssoParams);
      const ssoObject = JSON.parse(ssoStr);
      const backUrl = `${ssoObject.backUrl}?token=${this.token}&cardNo=${this.userInfo.cardNo}&sourceUrl=${ssoObject.sourceUrl}`;
      window.location.href = backUrl;
    } else {
      if (this.redirectUrl) {
        this.router.navigate([this.redirectUrl]);
      } else {
        if (this.backUrl) {
          window.location.href = this.backUrl;
        } else {
          this.router.navigate(['/creditBank/info']);
        }
        // this.router.navigate(['/uc/center/user']);
      }
    }
  }

  /**
   * 重置登录状态
   */
  logoutReset() {
    this.storageServe.removeStorage(['ucUserInfo', 'token', 'cardNoOfData']);
    this.cardNo = '';
    this.token = '';
    this.userInfo = null;
    this.isLoggedIn = false;
    this.operator = '';
    this.isInstitution = '';
    // this.router.navigate(['/index']);
  }
}
